package files

import (
	"../luahelper"
	lua "github.com/yuin/gopher-lua"
	"io/ioutil"
	"log"
	"path/filepath"
)

func RegisterFunc_4lua(l *lua.LState) {
	table := l.SetFuncs(l.NewTable(), map[string]lua.LGFunction{
		"Exists": Exists_4lua,
		"Read":   ReadFile_4lua,
		"Write":  WriteFile_4lua,
	})

	l.SetGlobal("Files", table)
}

func WriteFile_4lua(l *lua.LState) int {
	// Files.Write("file", "")
	file := l.ToString(1)
	text := l.ToString(2)

	err := ioutil.WriteFile(file, []byte(text), 0644)
	if err != nil {
		return luahelper.PushErrorMessage(l, err.Error())
	}

	return luahelper.PushStatus(l, true)
}

func ReadFile_4lua(l *lua.LState) int {
	fileName := l.ToString(1)

	bts, err := ioutil.ReadFile(fileName)
	if err != nil {
		luahelper.PushErrorMessage(l, err.Error())
	}

	return luahelper.PushStatusAndMessage(l, true, string(bts))
}

func Exists_4lua(l *lua.LState) int {
	p := l.ToString(1)
	abs_p, err := filepath.Abs(p)
	if err != nil {
		log.Println(err.Error())
		l.Push(lua.LBool(false))
	} else {
		exists := Exists(abs_p)
		l.Push(lua.LBool(exists))
	}

	return 1
}
